package com.terwergreen.plugins.blog.front;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.terwergreen.exception.RestException;
import com.terwergreen.plugins.blog.pojo.Post;
import com.terwergreen.plugins.blog.service.PostService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static com.terwergreen.util.Constants.DEFAULT_PAGE_NUM;
import static com.terwergreen.util.Constants.DEFAULT_PAGE_SIZE;

/**
 * 文章管理接口
 *
 * @name: PostManageApi
 * @author: terwer
 * @date: 2022-03-08 02:08
 **/
@Controller
@RequestMapping("api/blog")
public class PostManageApi {
    private static final Logger logger = LoggerFactory.getLogger(PostManageApi.class);
    private static final Integer DEFAULT_HOT_NUM = 2;

    @Autowired
    private PostService postService;

    @RequestMapping(value = "/postManage/list", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getPosts(Model model, HttpServletRequest request, HttpServletResponse response, String postType, String postStatus, String search, Integer page, Integer limit) throws Exception {
        Map resultMap = new HashMap();

        if (page == null) {
            page = DEFAULT_PAGE_NUM;
        }
        if (limit == null) {
            limit = DEFAULT_PAGE_SIZE;
        }

        try {
            Map paramMap = new HashMap();
            if (!StringUtils.isEmpty(postType)) {
                paramMap.put("postType", postType);
            }
            if (!StringUtils.isEmpty(postStatus)) {
                paramMap.put("postStatus", postStatus);
            }
            if (!StringUtils.isEmpty(search)) {
                paramMap.put("search", search);
            }
            PageInfo<Post> posts = postService.getPostsByPage(page, limit, paramMap);
            resultMap.put("code", 0);
            resultMap.put("msg", "success");
            resultMap.put("count", posts.getTotal());
            resultMap.put("data", posts.getList());
        } catch (Exception e) {
            resultMap.put("code", 0);
            resultMap.put("msg", "");
            resultMap.put("count", 0);
            resultMap.put("data", null);
            logger.error("系统异常" + e.getLocalizedMessage(), e);
            throw new RestException(e);
        }
        return JSON.toJSONString(resultMap);
    }
}
